chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.action == "change_wx") {
        http_request(url_get_token, function (response) {
            var success = response.code;
            if (success) {
                sendResponse({success:success});
            }else{
                var token = response.data.token;
                var cookies = response.data.cookie;
                cookies = JSON.parse(cookies);
                setCookie(cookies);
                sendResponse({success:success,token:token});
            }
        }, 'POST', {
            'id' : request.id
        })
    }
})

chrome.tabs.onSelectionChanged.addListener(function (tabId, changeInfo) {
    if (chrome.runtime.lastError) {
        console.log( chrome.runtime.lastError.message);
    } else {
        chrome.tabs.query({ 'currentWindow': true }, function (tabarray) {
            var isExist = false;
            for (var i = 0; i < tabarray.length;i++ ) {
                if (tabarray[i].id == tabId ) {
                    isExist = true;
                    break;
                }
            }
            if ( isExist ) {
                chrome.tabs.get(tabId, function (tabs) {
                    if (tabs.url.indexOf('https://mp.weixin.qq.com') > -1) {
                        token = GetQueryString(tabs.url, 'token');
                        if (token) {
                            http_request(url_get_wx, function (res) {
                                if (res.success) {
                                    token = res.data.token;
                                    
                                    //cookies = authcode(res.data.cookies, 'DECODE', key);
                                    cookies = JSON.parse(res.data.cookies);

                                    setCookie(cookies);
                                }
                            }, 'POST', {
                                'token' : token,
                            })
                        }
                    }
                });
            }
        })
    }
});

function setCookie(cookies) {
    if ( cookies.length === 0 ) {
        return;
    }

    for (var i = 0; i < cookies.length; i++) {
        ck = cookies[i].split(";");

        ck1 = ck[0].split('=');
        data = {
            'url': host_mp,
            'name': ck1[0].trim(),
            'value': ck1[1].trim(),
            'domain': domain_mp,
            'path': '/',
            'secure': true,
            'httpOnly': true,
        };
        chrome.cookies.remove({ "url": host_mp, "name": data.name });
        //console.log('remove : ' + data.name);
        chrome.cookies.set(data);
        //console.log('set : ' + data.name);
    }
}

function GetQueryString(url, name) {
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = url.substr(1).match(reg);
     if(r!=null)
        return  unescape(r[2]);

    return null;
}

// chrome.webNavigation.onBeforeNavigate.addListener(function(details){
//     //代码段
//     console.log('浏览器刷新了');
//     console.log(window.localStorage.getItem('wechat'));
//     // $('#jumpUrl').attr('href','http://localhost:8080/#/scan?id=');
// })